package com.mall.b2c.controller;

import com.mall.b2c.domain.store.StoreCityDomain;
import com.mall.b2c.domain.store.StoreDomain;
import com.mall.b2c.service.StoreCityService;
import com.mall.b2c.service.StoreService;
import com.mall.common.controller.BaseController;
import com.mall.common.domain.AreaDomain;
import com.mall.common.enums.FieldType;
import com.mall.common.exception.NoticeException;
import com.mall.common.service.AreaService;
import com.mall.common.util.ResponseUtils;
import com.mall.common.validation.annotation.RequiredFieldValidator;
import com.mall.common.validation.annotation.RequiredStringValidator;
import com.mall.common.validation.annotation.SpecialRegexFieldValidator;
import com.mall.common.validation.annotation.Validations;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by Misun on 2016/12/28.
 *  门店
 * */
@Controller
@RequestMapping("/admin/b2c/store")
public class StoreController extends BaseController {

    @Resource
    private StoreService storeService;
    @Resource
    private StoreCityService storeCityService;


    @RequestMapping(value="/list", method= RequestMethod.GET)
    public String list() {
        return "/admin/b2c/store/list";
    }

    @RequestMapping(value="/tree", method=RequestMethod.GET)
    public String tree(){
        return "/admin/b2c/store/tree";
    }

    @RequestMapping(value="/main", method=RequestMethod.GET)
    public String main(){
        return "/admin/b2c/store/main";
    }

    @RequestMapping(value="/treeData", method=RequestMethod.POST)
    @ResponseBody
    public List<StoreDomain> treeData(){
        StoreDomain s_store = StoreDomain.genRoot();
        List<StoreDomain> stores = storeService.getAll();
        stores.add(s_store);
        return stores;
    }

    @RequestMapping(value="/add", method=RequestMethod.GET)
    public String add(Long store_id, Model model){
        StoreDomain s_store = storeService.find(store_id);
        model.addAttribute("store", s_store);
        model.addAttribute("citys", storeCityService.getAll());
        return "/admin/b2c/store/input";
    }

    @Validations(
            requiredStrings = {
                    @RequiredStringValidator(fieldName="code",message="门店编码不能为空"),
                    @RequiredStringValidator(fieldName="name",message="门店名称不能为空"),
                    @RequiredStringValidator(fieldName="city.id",message="请选择门店城市")
            },
            specials = {
                    @SpecialRegexFieldValidator(fieldName="link_phone",fieldType= FieldType.mobileOrTelephone)
            }
    )
    @RequestMapping(value="/save", method=RequestMethod.POST)
    @ResponseBody
    public String save(StoreDomain store, HttpServletResponse response) throws Exception {
        if(store.getCode().contains(".")){
            StoreDomain upDept = storeService.get("code", StringUtils.substringBeforeLast(store.getCode(), "."));
            store.setUpDomain(upDept);
        }else{
            store.setUpDomain(null);
        }
        if (!storeService.isUnique("code", null, store.getCode())){
            throw new NoticeException("error.unique", new Object[]{"门店编码"});
        }
        store.setCity(storeCityService.find(store.getCity().getId()));
        storeService.persist(store);
        return ResponseUtils.renderJSON(store, response);
    }

    @RequestMapping(value="/update/{id}", method=RequestMethod.GET)
    public String update(@PathVariable Long id, Model model){
        StoreDomain store = storeService.find(id);
        model.addAttribute("store", store);
        return "/admin/b2c/store/add";
    }

    @Validations(
            requiredFields = {
                    @RequiredFieldValidator(fieldName="id", message= "门店不存在")
            },
            requiredStrings = {
                    @RequiredStringValidator(fieldName="code",message="门店编码不能为空"),
                    @RequiredStringValidator(fieldName="name",message="门店名称不能为空"),
                    @RequiredStringValidator(fieldName="city.id",message="请选择门店城市")
            },
            specials = {
                    @SpecialRegexFieldValidator(fieldName="link_phone",fieldType=FieldType.mobileOrTelephone)
            }
    )
    @RequestMapping(value="/update", method=RequestMethod.POST)
    @ResponseBody
    public String update(StoreDomain store, Long areaId, HttpServletResponse response){
        if(store.getCode().contains(".")){
            StoreDomain upDept = storeService.get("code", StringUtils.substringBeforeLast(store.getCode(), "."));
            store.setUpDomain(upDept);
        }else{
            store.setUpDomain(null);
        }
        if (!storeService.isUniqueById("code", store.getId(), store.getCode())){
            throw new NoticeException("error.unique", new Object[]{"门店编码"});
        }

        storeService.update(store);
        return ResponseUtils.renderJSON(store, response);
    }

    @Validations(
            requiredFields = {
                    @RequiredFieldValidator(fieldName="ids",message="门店不存在")
            }
    )
    @RequestMapping(value="/delete", method=RequestMethod.POST)
    public String delete(Long[] ids, HttpServletResponse response) {
        StoreDomain persistent = storeService.find(ids[0]);
        storeService.remove(ids);
        return ResponseUtils.renderJSON(persistent, response);
    }

    @RequestMapping(value="/checkCode", method=RequestMethod.POST)
    public String checkCode(String oldValue, String code, HttpServletResponse response){
        if (storeService.isUnique("code", oldValue, code)) {
            return ResponseUtils.renderJSON("true", response);
        } else {
            return ResponseUtils.renderJSON("false", response);
        }
    }
}
